package com.voxel.sense.infomsg.module.task.check;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.download.DownloadListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.OpenDocuIntentUtils;
import com.voxel.sense.infomsg.utils.UploadUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.TaskFileAndReportListEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.TaskNetHelper;

/**
 * Created by ChenYiYao on 2018/3/29.
 */

public class CheckTaskPresenter extends BasePresenter<CheckTaskContract.View>
        implements CheckTaskContract.Presenter, DataSource.Callback<BaseEntity<TaskFileAndReportListEntity>> {
    private boolean mIsLoading = false;
    private String mTaskNum;

    public CheckTaskPresenter(CheckTaskContract.View view) {
        super(view);
    }


    @Override
    public void start() {
        super.start();

    }


    @Override
    public void doSubmitPass(String taskNum, String taskId) {
        mTaskNum = taskNum;
        if (NetworkUtils.isConnected()) {
            mView.showLoading("");
            TaskNetHelper.taskAuditPass(taskNum, taskId, this);
        } else {
            mView.showError(Factory.app().getString(R.string.network_unavailable));
        }
    }

    @Override
    public void doSubmitUnpass(String taskNum, String taskId, String opinion) {
        mTaskNum = taskNum;
        if (NetworkUtils.isConnected()) {
            mView.showLoading("");
            TaskNetHelper.taskAuditRejct(taskNum, taskId, opinion, this);
        } else {
            mView.showError(Factory.app().getString(R.string.network_unavailable));
        }
    }

    @Override
    public void doLookDocFile(String path) {
        File cacheDir = AppFileUtil.getCacheDir();
        File file = new File(cacheDir, path);
        boolean fileExists = FileUtils.isFileExists(new File(cacheDir, path));
        if (fileExists) {
            //网络文件，但已存在
            OpenDocuIntentUtils.OpenFile(file, Factory.app());
        } else {
            DownFile(CommonConstants.FILE_TASK_URL, path, cacheDir);
        }
    }

    @Override
    public void doLoadTaskFile(String taskNum) {
        TaskNetHelper.getTaskFileAndReport(taskNum, this);
    }

    @Override
    public void doShowPageGallery(List<MultiItemBean<String>> datas, int position) {
        if (!ListUtil.isEmpty(datas)) {
            List<String> imageDatas = new ArrayList<>();
            int imagePosition = 0;
            for (int i = 0; i < datas.size(); i++) {
                MultiItemBean<String> itemBean = datas.get(i);
                if (itemBean.getType() == CheckTaskContract.TYPE_PHOTO) {
                    imageDatas.add(CommonConstants.FILE_TASK_URL + itemBean.getData());
                    if (i == position) {
                        imagePosition = imageDatas.size() - 1;
                    }
                }
            }
            mView.onShowPageGallery(imageDatas, imagePosition);
        }
    }


    @Override
    public void onDataLoaded(BaseEntity<TaskFileAndReportListEntity> data, int reqId) {
        if (mView == null) {
            return;
        }
        mView.dimissLoading();
        if (reqId == RequestIdFactory.GET_TASK_FILE_REPORT) {
            if (data.isSuccess() && data.getData() != null) {
                List<TaskFileAndReportListEntity.FileBean> file = data.getData().getFile();
                List<TaskFileAndReportListEntity.FormBean> form = data.getData().getForm();
                getTaskDataSuccess(file, form, data.getData().getFormContents());

            } else {
                mView.showEmptyView();
            }
        } else if (reqId == RequestIdFactory.TASK_AUDIT_PASS) {
            //通过审核
            if (data.isSuccess()) {
                EventBus.getDefault().post(new EventEntity(EventBusConstants.CHECK_TASK_PASS, mTaskNum));
                mView.onSubmitCheck(true);
            } else {
                mView.showSnackBarWarning("审核失败，请重新再试");
            }
        } else if (reqId == RequestIdFactory.TASK_AUDIT_REJECT) {
            //驳回
            if (data.isSuccess()) {
                //发送通知任务状态改变
                EventBus.getDefault().post(new EventEntity(EventBusConstants.CHECK_TASK_NO_PASS, mTaskNum));
                mView.onSubmitCheck(false);
            } else {
                mView.showSnackBarWarning("驳回失败，请重新再试");
            }
        }
    }


    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }
        if (reqId == RequestIdFactory.GET_TASK_FILE_REPORT) {
            mView.showEmptyView();
        } else if (reqId == RequestIdFactory.TASK_AUDIT_PASS) {

            mView.showSnackBarWarning("审核失败，请重新再试");
        } else if (reqId == RequestIdFactory.TASK_AUDIT_REJECT) {
            mView.showSnackBarWarning("驳回失败，请重新再试");
        }
        mView.dimissLoading();
    }


    private void getTaskDataSuccess(List<TaskFileAndReportListEntity.FileBean> file,
                                    List<TaskFileAndReportListEntity.FormBean> form, String formContents) {
        List<MultiItemBean<String>> imageList = new ArrayList<>();
        List<MultiItemBean<String>> docList = new ArrayList<>();

        if (!ListUtil.isEmpty(file)) {
            for (TaskFileAndReportListEntity.FileBean bean : file) {
                //判断是否是图片
                if (FileUtils.vertifyImage(bean.getFileName())) {
                    imageList.add(new MultiItemBean(bean.getFilePath(), CheckTaskContract.TYPE_PHOTO,
                            bean.getFileName()));
                } else if (!FileUtils.vertifyVedio(bean.getFileName())) {
                    //排除视频类文件
                    docList.add(new MultiItemBean(bean.getFilePath(), CheckTaskContract.TYPE_FILE,
                            bean.getFileName()));
                }
            }
        }

        //将数据装入结果集中
        List<MultiItemBean<String>> resultList = new ArrayList<>();
        if (!ListUtil.isEmpty(form)) {
            resultList.add(new MultiItemBean("报表", CheckTaskContract.TYPE_DESC,
                    ""));
            for (TaskFileAndReportListEntity.FormBean bean : form) {
                resultList.add(new MultiItemBean(bean.getName(), CheckTaskContract.TYPE_REPORT,
                        bean.getCode()));
            }
        }

        if (!ListUtil.isEmpty(imageList)) {
            resultList.add(new MultiItemBean("图片附件", CheckTaskContract.TYPE_DESC,
                    ""));
            resultList.addAll(imageList);
        }
        if (!ListUtil.isEmpty(docList)) {
            resultList.add(new MultiItemBean("其它附件", CheckTaskContract.TYPE_DESC,
                    ""));
            resultList.addAll(docList);
        }
        mView.onRefreshView(resultList, formContents);
    }


    private void DownFile(final String url, final String fileName, final File cacheDir) {
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
            return;
        }

        if (mIsLoading)
            return;

        UploadUtils.getInstent().getPostDownRequest(cacheDir.getAbsolutePath(), fileName, url + fileName, new DownloadListener(url + fileName) {
            @Override
            public void onStart(Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = true;
                mView.showLoading("", false);
            }

            @Override
            public void onProgress(Progress progress) {

            }

            @Override
            public void onError(Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.dimissLoading();
                ToastUtil.showToastLong(Factory.app(), "下载失败");
                FileUtils.deleteAllFile(new File(cacheDir, fileName));
            }

            @Override
            public void onFinish(File file, Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.dimissLoading();
                OpenDocuIntentUtils.OpenFile(file, Factory.app());
            }

            @Override
            public void onRemove(Progress progress) {
                if (mView == null)
                    return;
                mIsLoading = false;
                mView.dimissLoading();
            }
        });
    }

}

